#!/bin/bash

# 设置ISO路径和挂载点（请根据实际情况修改）
ISO_PATH="/root/CentOS-7-x86_64-DVD-2009.iso"
MOUNT_POINT="/mnt/cdrom"
REPO_FILE="/etc/yum.repos.d/local.repo"

# 检查 root 权限
if [ "$(id -u)" != "0" ]; then
    echo "错误：此脚本需要以 root 权限运行！"
    exit 1
fi

# 获取系统信息
detect_distro() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        DISTRO=$ID
        VERSION_ID=$(echo $VERSION_ID | cut -d '.' -f1)
    elif command -v lsb_release &>/dev/null; then
        DISTRO=$(lsb_release -si | tr '[:upper:]' '[:lower:]')
        VERSION_ID=$(lsb_release -sr | cut -d '.' -f1)
    else
        echo "无法识别系统类型，退出。"
        exit 1
    fi
}

detect_distro
echo "✅ 检测到系统：$DISTRO $VERSION_ID"

# 检查当前包管理器是 yum 还是 dnf
if command -v dnf &>/dev/null; then
    PKG_TOOL="dnf"
elif command -v yum &>/dev/null; then
    PKG_TOOL="yum"
else
    echo "❌ 未找到 yum 或 dnf 工具，请确认系统环境。"
    exit 1
fi

# 检查是否已有有效的本地源
if [ -f "$REPO_FILE" ]; then
    echo "⚠️ 检测到本地仓库配置文件，正在检查有效性..."
    if [ "$PKG_TOOL" == "dnf" ]; then
        $PKG_TOOL repolist | grep -i local &>/dev/null
    else
        $PKG_TOOL repolist | grep -i local &>/dev/null
    fi
    if [ $? -eq 0 ]; then
        echo "✅ 本地仓库已经正常工作。"
        exit 0
    else
        echo "❌ 本地仓库配置存在问题，准备重新配置..."
        rm -f "$REPO_FILE"
    fi
fi

# 创建挂载点
if [ ! -d "$MOUNT_POINT" ]; then
    mkdir -p "$MOUNT_POINT"
fi

# 挂载 ISO 文件
mounted=$(mount | grep "$MOUNT_POINT")
if [ -z "$mounted" ]; then
    echo "⏳ 正在挂载 ISO 文件到 $MOUNT_POINT ..."
    mount -o loop "$ISO_PATH" "$MOUNT_POINT"
    if [ $? -ne 0 ]; then
        echo "❌ 挂载失败，请确认ISO路径正确、文件未损坏或loop设备可用。"
        exit 1
    fi
else
    echo "✅ ISO 文件已经挂载。"
fi

# 根据不同系统生成对应的repo内容
cat > "$REPO_FILE" <<EOF
[local]
name=Local Repository
baseurl=file://$MOUNT_POINT
gpgcheck=0
enabled=1
EOF

# CentOS Stream / Rocky Linux 8+ 使用 BaseOS/AppStream 结构
if [[ "$DISTRO" == "centos" || "$DISTRO" == "rocky" ]] && (( VERSION_ID >= 8 )); then
    echo "🔧 检测为 CentOS Stream 8+/Rocky Linux 8+，更新 AppStream 和 BaseOS 配置..."

    cat > "$REPO_FILE" <<EOF
[local-baseos]
name=Local BaseOS Repository
baseurl=file://$MOUNT_POINT/BaseOS
gpgcheck=0
enabled=1

[local-appstream]
name=Local AppStream Repository
baseurl=file://$MOUNT_POINT/AppStream
gpgcheck=0
enabled=1
EOF
fi

# 清理缓存
echo "🧹 正在清理软件包缓存..."
$PKG_TOOL clean all &>/dev/null

# 列出仓库信息
echo "📋 正在列出可用仓库..."
$PKG_TOOL repolist

echo "✅ 本地 YUM/DNF 源配置已完成。"